﻿#include "SignalHandler.h"
#include <QFile>
#include <QDebug>
#include <QTextStream>
#include "BaseModule/IBaseSignal.h"
#include "BaseModule/AppManager.h"
#include "ScriptManager/PythonAgent.h"
#include <iostream>

namespace ScriptManager
{
    SignalHandler* SignalHandler::m_instance = nullptr;

    SignalHandler* SignalHandler::getInstance()
    {
        if (m_instance == nullptr)
        {
            m_instance = new SignalHandler;
        }
        return m_instance;
    }

    void SignalHandler::cleanup()
    {
        m_pythonAgent->finalize();
    }

    SignalHandler::SignalHandler()
    {
        auto _baseSignal = IBaseSignalInstance;
        connect(_baseSignal, &BaseModule::IBaseSignal::signal_execScriptManager, this, &SignalHandler::slot_execScriptManager, Qt::DirectConnection);
        connect(_baseSignal, &BaseModule::IBaseSignal::signal_execPYCode, this, &SignalHandler::slot_execPYCode);
        connect(_baseSignal, &BaseModule::IBaseSignal::signal_execScriptFile, this, &SignalHandler::slot_execScriptFile);
        connect(_baseSignal, &BaseModule::IBaseSignal::signal_saveScript, this, &SignalHandler::slot_saveScript);
        connect(_baseSignal, &BaseModule::IBaseSignal::signal_editScript, this, &SignalHandler::slot_editScript);
        connect(_baseSignal, &BaseModule::IBaseSignal::signal_setPythonIsDebug, this, &SignalHandler::slot_setPythonIsDebug);
        connect(_baseSignal, &BaseModule::IBaseSignal::signal_execExampleScriptCode, this, &SignalHandler::slot_execExampleScriptCode);
        connect(_baseSignal, &BaseModule::IBaseSignal::signal_execSmartScriptCode, this, &SignalHandler::slot_execSmartScriptCode);

        m_isGUI = AppManagerInstance->getIsGUI();

        m_pythonAgent = PythonAgent::getInstance();
        m_pythonAgent->initialize();

    }

    void SignalHandler::slot_execScriptManager(BaseModule::EScriptManager type)
    {
        if (m_pythonAgent)
        {
            if (type == BaseModule::EScriptManager::Init)
            {
                m_pythonAgent->initialize();
            }
            else if (type == BaseModule::EScriptManager::Finalize)
            {
                m_pythonAgent->finalize();
            }
            else if (type == BaseModule::EScriptManager::Unlock)
            {
                m_pythonAgent->unLock();
            }
            else if (type == BaseModule::EScriptManager::Stop)
            {
                m_pythonAgent->stopScript();
            }
            else if (type == BaseModule::EScriptManager::Restart)
            {
                m_pythonAgent->restartRecordScript();
            }
        }
    }

    void SignalHandler::slot_execPYCode(QStringList codes, bool save, bool exec)
    {
        m_pythonAgent->submit(codes, save, exec);
        if (save && !exec)
        {
            for (auto _code : codes)
            {
                qDebug() << "save Script :" << _code;
            }
            qDebug() << "\n";
        }
    }

    /// @brief 执行脚本文件

    bool SignalHandler::slot_execScriptFile(QString filePath, bool isNoGui, QStringList listPara)
    {
        return m_pythonAgent->execScriptFile(filePath, isNoGui, listPara);
    }

    /// @brief 保存脚本

    void SignalHandler::slot_saveScript(QString filePath)
    {
        m_pythonAgent->saveScript(filePath);
    }

    /// @brief 执行案例脚本中的python代码

    void SignalHandler::slot_execExampleScriptCode(QStringList listCode)
    {
        QStringList pyCommands;
        for (auto _code : listCode)
        {
            if (!_code.startsWith('#'))
            {
                pyCommands.append(_code);
            }
        }
        if (m_pythonAgent->isScriptRuning())
        {
            m_pythonAgent->appendCommandToPyThread("", pyCommands);
            m_pythonAgent->setIsImportExample();
        }
        else
        {
            m_pythonAgent->execScriptCode(pyCommands, !m_isGUI);
            m_pythonAgent->setIsImportExample();
        }
        m_pythonAgent->unLock();
    }

    /// @brief 执行python代码脚本，并且在脚本运行前执行一些其它python代码

    void SignalHandler::slot_execSmartScriptCode(QString filePath, QStringList listCode)
    {
        if (m_pythonAgent->isScriptRuning())//脚本运行中直接添加命令
        {
            QFile _file(filePath);
            if (!_file.open(QIODevice::Text | QIODevice::ReadOnly))
            {
                emit IBaseSignalInstance->signal_showMessageToConsole(BaseModule::EMessageConsole::Error, tr("Script open failed"));
                m_pythonAgent->unLock();
                m_pythonAgent->stopScript();
                return;
            }

            QStringList commandList;
            QTextStream _stream(&_file);
            _stream.setCodec("UTF-8");
            while (!_stream.atEnd())
            {
                QString line = _stream.readLine().simplified();
                if (!line.contains('#'))
                {
                    commandList.append(line);
                }
            }
            _file.close();
            m_pythonAgent->appendCommandToPyThread(filePath, commandList);
            m_pythonAgent->unLock();
        }
        else//脚本没有运行则创建脚本执行
        {
            bool result = m_pythonAgent->execScriptFile(filePath, !m_isGUI, listCode);
            if (!result)
            {
                m_pythonAgent->unLock();
            }
        }
    }

    /// @brief 设置python是否为调试模式

    void SignalHandler::slot_setPythonIsDebug(bool isDebug)
    {
        m_pythonAgent->setDebug(isDebug);
        m_pythonAgent->unLock();
    }

    void SignalHandler::slot_editScript(QString filePath, QString text)
    {
        QFile file(filePath);
        if (!file.open(QIODevice::Text | QIODevice::WriteOnly))
        {
            emit IBaseSignalInstance->signal_showMessageToConsole(BaseModule::EMessageConsole::Error, tr("Script open failed"));
            return;
        }

        QTextStream out(&file);
        out.setCodec("UTF-8");
        out << text;

        file.close();
    }
}
